package org.example.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.ConnectException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

/**
 * AlertSenderRunner
 *
 * @author: wangchao
 * @Date: 2025/6/10 20:10
 * @since 7.0.0-RC2
 **/
@Slf4j
@Component
public class AlertSenderRunner implements ApplicationRunner {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final String LOG_FILE_PATTERN2 = "system_alarm-\\d{4}-\\d{2}-\\d{2}_\\d{6}-current.log";
    private static final String LOG_FILE_PATTERN = "system_alarm-test-current.log";
    @Resource
    private AlertSenderService alertSenderService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        alertSenderService.connectingAgentServer();
        Path currentDir = Paths.get(System.getProperty("user.dir"));
        // read local file log and parse to alert
        // system_alarm-2025-05-27_192736-current
        Path logFilePath = findLogFile(currentDir);
        if (logFilePath != null) {
            try {
                // 读取并解析日志文件
                try (BufferedReader reader = Files.newBufferedReader(logFilePath)) {
                    String line;
                    long lineSize = 0;
                    while ((line = reader.readLine()) != null) {
                        // 跳过空行
                        if (line.trim().isEmpty()) {
                            continue;
                        }
                        ThreadUtil.safeSleep(300);
                        try {
                            // 解析JSON行
                            Alert alert = objectMapper.readValue(line, Alert.class);
                            alertSenderService.sendAlert(alert);
                            lineSize++;
                            // log.info("Alert sent: {}", alert);
                        } catch (JsonProcessingException e) {
                            log.error("Failed to parse alert line: {}", line, e);
                            // 继续解析下一行
                        }
                    }
                    log.info("Alert send {} finished", lineSize);
                }
            } catch (ConnectException ex) {
                log.error("Failed to connect to the server", ex);
                alertSenderService.connectingAgentServer();
            } catch (IOException e) {
                log.error("Error reading or parsing log file", e);
                throw new RuntimeException("Failed to process alert log file", e);
            }
        } else {
            log.warn("No log file found matching the pattern");
        }
        System.exit(0);
    }

    private Path findLogFile(Path directory) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory,
            path -> path.getFileName().toString().matches(LOG_FILE_PATTERN))) {
            Iterator<Path> it = stream.iterator();
            if (it.hasNext()) {
                return it.next();
            }
        } catch (IOException e) {
            log.error("Error searching for log file", e);
        }
        return null;
    }

    private List<Alert> parseLogFile(Path filePath) throws IOException {
        List<Alert> alerts = new ArrayList<>();
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }
                try {
                    // 解析JSON行
                    Alert alert = objectMapper.readValue(line, Alert.class);
                    alerts.add(alert);
                } catch (JsonProcessingException e) {
                    log.error("Failed to parse alert line: {}", line, e);
                    // 继续解析下一行
                }
            }
        }
        return alerts;
    }
}
